package com.xunji.xunji.module.trace.controller;

import android.util.Log;

import com.amap.api.maps.model.LatLng;
import com.google.gson.Gson;
import com.huanxiao.base.net.RespResult;
import com.huanxiao.util.CtxHelper;
import com.huanxiao.util.DateHelper;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.xunji.xunji.controller.QiniuManager;
import com.xunji.xunji.db.dao.TraceDao;
import com.xunji.xunji.db.dao.TraceImageDao;
import com.xunji.xunji.db.dao.TraceRecordDao;
import com.xunji.xunji.module.account.controller.UserAccount;
import com.xunji.xunji.module.trace.bean.MoveRecordVO;
import com.xunji.xunji.module.trace.bean.PhotoRecordVO;
import com.xunji.xunji.module.trace.dao.Trace;
import com.xunji.xunji.module.trace.dao.TraceImage;
import com.xunji.xunji.module.trace.dao.TraceRecord;
import com.xunji.xunji.module.trace.en.TraceTypeEnum;
import com.xunji.xunji.module.trace.mvp.model.TrackModel;
import com.xunji.xunji.net.ParamManager;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Paul on 2017/2/12.
 */
public class TraceManager {


    private TraceDao traceDao;
    private TraceImageDao traceImageDao;
    private TraceRecordDao traceRecordDao;
    private boolean isStart;
    private static TraceManager instance;

    private boolean isFinish = false;
    private double aDouble = 0;

    private int traceId = DateHelper.getCurrentSecond();


    private TraceRecord traceRecord = new TraceRecord();
    private List<Trace> traceList = new ArrayList<>();


    private TrackModel trackModel;

    private TraceManager() {
        traceDao = new TraceDao(CtxHelper.getApp());
        traceImageDao = new TraceImageDao(CtxHelper.getApp());
        traceRecordDao = new TraceRecordDao(CtxHelper.getApp());
        trackModel = new TrackModel();
    }


    public static TraceManager getInstance() {
        if (instance == null) {
            instance = new TraceManager();
        }

        return instance;
    }

    public boolean isStart() {
        return isStart;
    }

    public void setStart(boolean start) {
        isStart = start;
    }


    /**
     * 开始轨迹
     *
     * @param start
     */
    public void startTrace(LatLng start) {

        //开始轨迹，保存一条记录
        traceRecord.setId(traceId);
        traceRecord.setStartTime(new Date());
        traceRecord.setStartLongitude(start.longitude);
        traceRecord.setStartLatitude(start.latitude);
        traceRecordDao.save(traceRecord);
        setStart(true);

    }

    /**
     * 结束轨迹
     *
     * @param stop
     */
    public void stopTrace(LatLng stop, String title) {

        //保存轨迹点信息
        for (Trace trace : traceList) {
            traceDao.saveTrace(trace);
        }

        //更新这条轨迹信息
        traceRecord.setStopTime(new Date());
        traceRecord.setStopLongitude(stop.longitude);
        traceRecord.setStopLatitude(stop.latitude);
        traceRecord.setTitle(title);

        traceRecordDao.update(traceRecord);

        setStart(false);
        isFinish = true;

    }


    /**
     * 上传图片
     */
    public void uploadPhoto(final String title, final Subscriber<RespResult> subscriber) {
        final List<TraceImage> images = traceImageDao.getListByTraceId(traceId);
        if (images==null||images.size()==0){
            upload(title,subscriber);
        }else {
            UploadManger uploadManger = new UploadManger(images, new UploadManger.IUploadFinishListener() {
                @Override
                public void onUploadFinish() {
                    upload(title, subscriber);
                }

                @Override
                public void onItemFinish(int position, Object object) {

                }

                @Override
                public void onFailed() {
                    subscriber.onError(null);
                }
            });
            uploadManger.upload();
        }

    }


    /**
     * 上传轨迹
     *
     * @param title
     */
    public void upload(String title, final Subscriber<RespResult> subscriber) {

        List<MoveRecordVO> list = new ArrayList<>();
        for (Trace trace : traceList) {
            list.add(new MoveRecordVO(trace.getLatitude(), trace.getLongitude()));
        }
        String moveJson = new Gson().toJson(list);

        List<TraceImage> images = traceImageDao.getListByTraceId(traceId);


        List<PhotoRecordVO> recordVOs = new ArrayList<>();
        for (TraceImage image : images) {
            PhotoRecordVO vo = new PhotoRecordVO();
            vo.setLatitude(image.getLatitude());
            vo.setLongitude(image.getLongitude());
            vo.setDescription(image.getContent());
            vo.setImageUrl(image.getImagePaths());

            recordVOs.add(vo);
        }

        String photoJson = new Gson().toJson(recordVOs);

        trackModel.createTrackAllInfo(ParamManager.uploadTrack(UserAccount.getInstance().getNickname(), traceRecord.getStartLongitude(), traceRecord.getStartLongitude(),
                traceRecord.getStopLongitude(), traceRecord.getStopLatitude(), traceRecord.getStartTime(), traceRecord.getStopTime(),
                traceRecord.getStartAddress(), traceRecord.getStopAddress(), title, moveJson, photoJson)).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<RespResult>() {
            @Override
            public void onCompleted() {
                if (subscriber != null) {
                    subscriber.onCompleted();
                }

            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                if (subscriber != null) {
                    subscriber.onError(e);
                }
            }

            @Override
            public void onNext(RespResult respResult) {
                Log.e("HPG", respResult.getMessage());
                traceRecord.setUpload(true);
                traceRecordDao.update(traceRecord);

                if (subscriber != null) {
                    subscriber.onNext(respResult);
                }
            }
        });

    }

    public boolean isFinish() {
        return isFinish;
    }

    public void setFinish(boolean finish) {
        isFinish = finish;
    }

    public void pauseTrace(boolean isStart) {
        if (isStart) {
            setStart(false);
        } else {
            setStart(true);
        }
    }

    public void savePoint(LatLng latLng, double altitude, Integer traceType) {


        Trace trace = new Trace();
        trace.setDate(new Date());
        trace.setLatitude(latLng.latitude);
        trace.setLongitude(latLng.longitude);
        trace.setAltitude(altitude);
        trace.setType(traceType);
        trace.setTraceId(traceId);
        traceList.add(trace);

//        traceDao.saveTrace(trace);
    }

    public int getTraceId() {
        return traceId;
    }

    public List<LatLng> getLatlngList() {
        List<LatLng> latLngs = new ArrayList<>();
        for (Trace trace : traceList) {
            latLngs.add(new LatLng(trace.getLatitude(), trace.getLongitude()));
        }
        return latLngs;
    }


    public void reset() {
        traceList.clear();
        instance = null;
    }


    public TraceImage getTraceImageByPosition(LatLng latLng) {
        return traceImageDao.getTraceByPosition(latLng.latitude, latLng.longitude);
    }

    public TraceImage getTraceImageById(int id) {
        return traceImageDao.getTraceImageById(id);
    }


    public void delete(int traceId) {
        traceRecordDao.delete(traceId);
        traceDao.delete(traceId);

    }


    public void clear(){
        traceList.clear();
        traceRecord = null;
        traceId = DateHelper.getCurrentSecond();
        isFinish = false;
    }
}
